package com.xd100.lzll.gm.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

public class FileUtil {

	private HSSFWorkbook workbook;

	public static List<String[]> loadExecl(HttpServletRequest request)
			throws Exception {
		FileUtil f = new FileUtil();
		return f.mainloadExecl(request);
	}

	public List<String[]> mainloadExecl(HttpServletRequest request)
			throws Exception {
		DiskFileItemFactory fac = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(fac);
		upload.setHeaderEncoding("utf-8");
		List<FileItem> fileList = null;
		fileList = upload.parseRequest(request);
		ArrayList<String[]> csvList = new ArrayList<String[]>();
		Iterator<FileItem> it = fileList.iterator();
		while (it.hasNext()) {
			FileItem item = it.next();
			if (!item.isFormField()) {
				String name = item.getName();
				if (name == null || name.trim().equals("")) {
					continue;
				}
				InputStreamReader read = null;
				try {
					try {
						// 获取工作薄workbook
						workbook = new HSSFWorkbook(item.getInputStream());
						// 得到第一个单元的消息
						List<List<String>> datas = getDatasInSheet(0);
						for (List<String> li : datas) {
							if ("".equals(li.get(li.size() - 1))) {
								continue;
							}
							csvList.add(objlistToStringArray(li));
						}
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (read != null) {
						read.close();
					}
				}
			}
		}
		return csvList;
	}

	public List<List<String>> getDatasInSheet(int sheetNumber) {
		List<List<String>> result = new ArrayList<List<String>>();
		// 获得指定的sheet
		HSSFSheet sheet = workbook.getSheetAt(sheetNumber);
		// 获得sheet总行数
		int rowCount = sheet.getLastRowNum();
		if (rowCount < 1) {
			return result;
		}
		// 遍历行row
		for (int rowIndex = 0; rowIndex <= rowCount; rowIndex++) {
			// 获得行对象
			HSSFRow row = sheet.getRow(rowIndex);
			if (null != row) {
				List<String> rowData = new ArrayList<String>();
				// 获得本行中单元格的个数
				int cellCount = row.getLastCellNum();
				// 遍历列cell
				for (int cellIndex = 0; cellIndex < cellCount; cellIndex++) {
					HSSFCell cell = row.getCell(cellIndex);
					// 获得指定单元格中的数据
					String cellStr = getCellString(cell).toString();
					// String cellSre = cell.getStringCellValue();
					rowData.add(cellStr);
				}
				result.add(rowData);
			}
		}
		return result;
	}

	public String[] objlistToStringArray(List<String> strlist) {
		String[] strarry = new String[strlist.size()];
		int index = 0;
		for (String str : strlist) {
			strarry[index] = str;
			index++;
		}
		return strarry;
	}

	private Object getCellString(HSSFCell cell) {
		Object result = "";
		if (cell != null) {
			// 单元格类型：Numeric:0,String:1,Formula:2,Blank:3,Boolean:4,Error:5
			int cellType = cell.getCellType();
			switch (cellType) {
				case HSSFCell.CELL_TYPE_STRING:
					result = cell.getRichStringCellValue().getString();
					break;
				case HSSFCell.CELL_TYPE_NUMERIC:
					result = cell.getNumericCellValue();
					break;
				case HSSFCell.CELL_TYPE_FORMULA:
					result = cell.getNumericCellValue();
					break;
				case HSSFCell.CELL_TYPE_BOOLEAN:
					result = cell.getBooleanCellValue();
					break;
				case HSSFCell.CELL_TYPE_BLANK:
					result = "";
					break;
				case HSSFCell.CELL_TYPE_ERROR:
					result = "";
					break;
				default:
					System.out.println("枚举了所有类型");
					break;
			}
		}
		return result;
	}
}
